
import urllib2
import json
from hashlib import md5

from settings import MAMBA_SECRET_KEY


"""def check_auth_key( params ):
	
	$auth_key = params['auth_key']    
    
    del params['auth_key']
    
    ksort(params)

    data_arr = [ ( k, params[ k ] ) for k in sorted( params.keys() ) ]
    
    result = ''
    
	params_str = "&".join( [ "{0}={1}".format( d[ 0 ], d[ 1 ] ) for d in data_arr ] )
	
	for key, value in params.iteritems():
		result += "{0}={1}".format( key, value )

	return auth_key == md5( result + SECRET_KEY ).hexdigest()"""
	

"""<?php
header('Content-Type: text/html; charset=UTF-8');
ini_set('display_errors','On');
ini_set('error_reporting',E_ALL);
define('APP_ID',1);
define('SECRET_KEY','');
define('PLATFORM_GATEWAY','http://api.aplatform.ru?');

function check_auth_key($input)
{
    $auth_key = $input['auth_key'];
    unset($input['auth_key']);
    ksort($input);
    $result = '';
    foreach ($input as $key => $value){
        $result .= "$key=$value";
    }
    return $auth_key == md5($result . SECRET_KEY);
}

//if(!check_auth_key($_GET)) die('Invalid Auth Key ');

class MambaPlatform
{
    private function sign_server_server(array $request_params){
        ksort($request_params);
        $params = '';
        foreach ($request_params as $key => $value) {
            $params .= "$key=$value";
        }
        return md5($params . SECRET_KEY);
    }

    private function send_request($method, $input)
    {
        $request_params = array(
            'method'    => $method,
            'app_id'    => APP_ID,
            'format'    => 'JSON',
            'sid'        => $_GET['sid'],
            'secure'    => 1
        ) + $input;
        $request_params['sig'] = $this->sign_server_server($request_params);

        $params = '';
        foreach ($request_params as $key => $value) {
            $params .= ($params?'&':'')."$key=$value";
        }

        $request_str = PLATFORM_GATEWAY.$params;
        print $request_str."<br><br>";
        $res = json_decode(file_get_contents($request_str),true);
        print '<pre>'; print_r($res); print '</pre>';
        return $res;
    }

    public function anketa_getInfo($oid)
    {
        return $this->send_request(
            'anketa.getInfo',
            array(
                'oids' => $oid,
            )
        );
    }

    public function anketa_getHitlist()
    {
        return $this->send_request(
            'anketa.getHitlist',
            array(
                'period'    => -1,
                'limit'        => 100,
                'offset'    => 0,
//                'ids_only'    => 1
            )
        );
    }

    public function notify_sendMessage(array $oids, $text)
    {
        return $this->send_request(
            'notify.sendMessage',
            array(
                'oids'    => implode(',',$oids),
                'message'  => $text,
            )
        );
    }
}"""

def _request( url, data ):

	params = ""

	data_arr = [ ( k, data[ k ] ) for k in sorted( data.keys() ) ]
	
	params = "".join( [ "{0}={1}".format( d[ 0 ], d[ 1 ] ) for d in data_arr ] )
	req_params = "&".join( [ "{0}={1}".format( d[ 0 ], d[ 1 ] ) for d in data_arr ] )

	sig = md5( params + MAMBA_SECRET_KEY ).hexdigest()

	req_params += "&sig=" + sig

	full_url = url + "?" + req_params
	
	req = urllib2.Request( full_url )
	f = urllib2.urlopen( req )
	return f.read()

class ApiRequest:
	_URL = "http://api.aplatform.ru"	

	_ALL_BLOCKS = "about,location,flags,familiarity,type,interests"

	def __init__( self, appId, user_id, sid ):
		self._app_id = appId
		self._user_id = user_id
		self._sid = sid

	def _request( self, data ):
		data.update( app_id = self._app_id )
		data.update( sid = self._sid )
		data.update( secure = 1 )
		data.update( format = "JSON" )

		return _request( ApiRequest._URL, data )

	def search( self, offset, iam, look_for, min_age, max_age, country_id, region_id, city_id = None ):
		search_d =	{
						'method': "search.get",
						'iam': iam,
						'offset': offset,
						'look_for': look_for,
						'age_from': min_age,
						'age_to': max_age,
						#'with_photo': "1",
						#'real_only': "1",
						#'country_id': country_id,
						#'region_id': region_id,
						'blocks': ApiRequest._ALL_BLOCKS # problem is here
		}

		print "# search_d={0}".format( search_d )

		#if city_id != None:
		#	search_d.update( city_id = city_id )

		result = json.loads( self._request( search_d ) )

		return result

	def is_online( self ):
		#anketa.isOnline

		result = json.loads( 
			self._request(	
				{   
					'method': "anketa.isOnline"
				}
			) 
		)

		return result

	def test_req( self ):
		result = json.loads(
			self._request(
				{
					'method': "geo.getCountries"
				}
			)
		)

		return result

	def get_anketas( self, oids ):
		" oids is comma-separated values"
		result = json.loads( 
			self._request(	
				{   
					'method': "anketa.getInfo",
					'oids': ",".join( oids ),
					'blocks': ApiRequest._ALL_BLOCKS,
					'sid': self._sid
				}
			) 
		)

		return result
		

	def get_contact_list( self ):		
		result = json.loads( 
			self._request(	
				{   
					'method': "contacts.getContactList",
					'blocks': ApiRequest._ALL_BLOCKS,
					'sid': self._sid
				}
			) 
		)

		return result
		

	
	
	